//
//  SWPageGenerateOperation.swift
//  YiyaPuzzleDemo
//
//  Created by linhan on 16/10/20.
//  Copyright © 2016年 test. All rights reserved.
//

import Foundation
class SWPageGenerateOperation: Operation
{
    var task:SWGenerationTask
    var page:SWPage = SWPage()
    var successCallback:((SWGenerationTask)->Void)?
    
    
    private var _largeBgImage:UIImage?
    
    init?(task:SWGenerationTask)
    {
        self.task = task
        super.init()
        guard let page = task.page else{
            return nil
        }
        self.page = page
        
        if let largeBgURL = page.largeBgURL,
            SWDownloadManager.sharedManager().getImage(largeBgURL) == nil
        {
            let downloadTask = SWDownloadTask(url: largeBgURL)
            let downloadOperation = SWDownloadOperation(task: downloadTask)
            self.addDependency(downloadOperation)
            SWDownloadManager.sharedManager().addOperation(downloadOperation, priority:.veryHigh)
        }
    }
    
    func update(_ task:SWGenerationTask)
    {
        self.task = task
        if let page = task.page
        {
            self.page = page
        }
    }
    
    //合成打印图极其预览图(1.large.jpg 1.preview.jpg)
    override func main()
    {
        if let largeBgURL = page.largeBgURL, largeBgURL != ""
        {
            _largeBgImage = SWDownloadManager.sharedManager().getImage(largeBgURL)
            
        }
        
        var images:[(SWPhoto, UIImage)] = []
        let photos:[SWPhoto] = page.photos?.flatMap({$0 as? SWPhoto}) ?? []
        for photo in photos
        {
            if let imageID = photo.imageID,
               let image = SWBookAssetManager.sharedManager().getImage(imageID, level: .processed)
            {
                images.append((photo, image))
            }
        }
        
        drawImage(images, level: .origin)
        drawImage(images, level: .preview)
        trace("Generate")
        
        successCallback?(task)
    }
    
    private func drawImage(_ photos:[(SWPhoto, UIImage)], level:SWPhotoSizeLevel)
    {
        let size = level == .origin ? SW.Config.BookSinglePageSize : SW.Config.BookSinglePagePreviewSize
        UIGraphicsBeginImageContextWithOptions(size, false, 1)
        
        for (photo, image) in photos
        {
            let x:CGFloat = valueCorrection(size.width * CGFloat(photo.xPercent), min: 0, max: size.width)
            let y:CGFloat = valueCorrection(size.height * CGFloat(photo.yPercent), min: 0, max: size.height)
            let width:CGFloat = valueCorrection(size.width * CGFloat(photo.widthPercent), min: 0, max: size.width - x)
            let height:CGFloat = valueCorrection(size.height * CGFloat(photo.heightPercent), min: 0, max: size.height - y)
            let rect = CGRectMake(x, y, width, height)
            if width > 0 && height > 0
            {
                image.draw(in: rect)
            }
        }
        
        _largeBgImage?.draw(in: CGRectMake(0, 0, size.width, size.height))
        
        if let texts = page.texts?.flatMap({$0 as? SWText}).filter({($0.text ?? "").length > 0})
        {
            for text in texts
            {
                let x:CGFloat = valueCorrection(size.width * CGFloat(text.xPercent), min: 0, max: size.width)
                let y:CGFloat = valueCorrection(size.height * CGFloat(text.yPercent), min: 0, max: size.height)
                let width:CGFloat = valueCorrection(size.width * CGFloat(text.widthPercent), min: 0, max: size.width - x)
                let height:CGFloat = valueCorrection(size.height * CGFloat(text.heightPercent), min: 0, max: size.height - y)
                
                let PPRatio:CGFloat = 300 / 72
                var fontSize:CGFloat = CGFloat(text.fontSize ??? 0) ??? SW.Config.Template.FontSize
                fontSize = level == .origin ? (fontSize * PPRatio) : (fontSize * UIScreen.main.scale)
                let textLeading:CGFloat = SW.Config.Template.TextLeading * (level == .origin ? PPRatio : UIScreen.main.scale)
                let font = UIFont.systemFont(ofSize: fontSize)
                let content:String = text.text ?? ""
                let color = UIColor(hex: text.textColor ??? "0x0")
                let contentWidth:CGFloat = width
                let contentHeight:CGFloat = StringUtil.getStringHeight(content, font: font, width: width, lineSpacing:textLeading)
                let rect = CGRectMake(x, y, contentWidth, min(contentHeight, height))
                let paragraphStyle:NSMutableParagraphStyle = NSMutableParagraphStyle()
                paragraphStyle.alignment = .left
                paragraphStyle.lineBreakMode = .byWordWrapping
                paragraphStyle.lineSpacing = textLeading
                (content as NSString).draw(in: rect, withAttributes: [NSFontAttributeName:font, NSForegroundColorAttributeName:color, NSParagraphStyleAttributeName:paragraphStyle])
            }
        }
        
        let result:UIImage? = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        if let result = result
        {
            savePhoto(result, level: level)
        }
    }
    
    //保存图片到对应的规格
    private func savePhoto(_ image:UIImage, level:SWPhotoSizeLevel)
    {
        if let data = UIImageJPEGRepresentation(image, 0.9),
            let pageID = page.pageID, pageID != ""
        {
            let path = SWPageManager.sharedManager().fetchStorePath(page, level: level)
            if level == .origin
            {
                //要打印的图存为300DPI
                let newData = SWImageUtil.changeImageResolution(data, resolution: 300) ?? data
                FileUtility.saveImageCacheToPath(path, image:newData)
            }
            else
            {
                FileUtility.saveImageCacheToPath(path, image:data)
            }
        }
    }
    
    //值纠正
    private func valueCorrection(_ value:CGFloat, min minValue:CGFloat, max maxValue:CGFloat) -> CGFloat
    {
        return min(max(value, minValue), maxValue)
    }
    
    
}
